import CryptoJS from 'crypto-js';

// 必须为16、24、32位
const KEY = "zGYMLvtMJQuBh91r";
const IV = "T1wRiUqbrpyN7bps";

/**
 * AES加密 ：字符串 key iv  返回base64
 */
export const Encrypt = (word: any, keyStr = KEY, ivStr = IV): any => {
    if(keyStr.length != 16 && keyStr.length != 24 && keyStr.length != 32){
        return "keyStr length must be 16,24,32";
    }
    const key = CryptoJS.enc.Utf8.parse(keyStr);
    const iv = CryptoJS.enc.Utf8.parse(ivStr);
    const srcs = CryptoJS.enc.Utf8.parse(word);
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding});
    return encrypted.toString();
};

/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 * @return {string}
 */
export const Decrypt = (word: any, keyStr = KEY, ivStr = IV): any => {
    if(keyStr.length != 16 && keyStr.length != 24 && keyStr.length != 32){
        return "keyStr length must be 16,24,32";
    }
    const key = CryptoJS.enc.Utf8.parse(keyStr);
    const iv = CryptoJS.enc.Utf8.parse(ivStr);
    const decrypt = CryptoJS.AES.decrypt(word, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding});
    return CryptoJS.enc.Utf8.stringify(decrypt);
};


export const generateKey = (num: number) => {
        let library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let key = "";
        for (let i = 0; i < num; i++) {
            let randomPoz = Math.floor(Math.random() * library.length);
            key += library.substring(randomPoz, randomPoz + 1);
        }
        return key;
}